<template>
  <div class="share">
    <div class="header">
      <div class="header-content">
        <div class="logo" @click="jump">
          <span class="iconfont icon-pan"></span>
          <span class="name">密波智造云盘</span>
        </div>
      </div>
    </div>
    <div class="share-body">
      <template v-if="Object.keys(shareInfo).length == 0">
        <div v-loading="Object.keys(shareInfo).length == 0" class="loading"></div>
      </template>
      <template v-else>
        <div class="share-panel">
          <div class="share-user-info">
            <div class="avatar">
              <Avatar :userId="shareInfo.userId" :avatar="shareInfo.avatar" :width="50"></Avatar>
            </div>
            <div class="share-info">
              <div class="user-info">
                <span class="nick-name">{{ shareInfo.nickName }} </span>
                <span class="share-time">分享于 {{ shareInfo.shareTime }}</span>
              </div>
              <div class="file-name">分享文件：{{ shareInfo.fileName }}</div>
            </div>
          </div>
          <div class="share-op-btn">
            <el-button type="primary" v-if="shareInfo.currentUser" @click="cancelShare"><span
                class="iconfont icon-cancel"></span>取消分享</el-button>
            <el-button v-else type="primary" :disabled="selectFileIdList.length == 0" @click="save2MyPan"><span
                class="iconfont icon-import"></span>保存到我的网盘</el-button>
          </div>
        </div>
        <!--导航-->
        <Navigation ref="navigationRef" @navChange="navChange" :shareId="shareId"></Navigation>
        <div class="file-list">
          <Table :columns="columns" :showPagination="true" :dataSource="tableData" :fetch="loadDataList"
            :initFetch="false" :options="tableOptions" :showPageSize="false" @rowSelected="rowSelected">
            <template #fileName="{ index, row }">
              <div class="file-item" @mouseenter="showOp(row)" @mouseleave="cancelShowOp(row)">
                <template v-if="
                  (row.fileType == 3 || row.fileType == 1) && row.status !== 0
                ">
                  <icon :cover="row.fileCover"></icon>
                </template>
                <template v-else>
                  <icon v-if="row.folderType == 0" :fileType="row.fileType"></icon>
                  <icon v-if="row.folderType == 1" :fileType="0"></icon>
                </template>
                <span class="file-name" :title="row.fileName">
                  <span @click="preview(row)">{{ row.fileName }}</span>
                </span>
                <span class="op">
                  <span v-if="row.folderType == 0" class="iconfont icon-download"
                    @click="download(row.fileId)">下载</span>
                  <template v-if="row.showOp && !shareInfo.currentUser">
                    <span class="iconfont icon-import" @click="save2MyPanSingle(row)">保存到我的网盘</span>
                  </template>
                </span>
              </div>
            </template>
            <template #fileSize="{ index, row }">
              <span v-if="row.fileSize">
                {{ proxy.Utils.sizeToStr(row.fileSize) }}</span>
            </template>
          </Table>
        </div>
      </template>
      <!--选择目录-->
      <FolderSelect ref="folderSelectRef" @folderSelect="save2MyPanDone"></FolderSelect>
      <!--预览-->
      <Preview ref="previewRef"> </Preview>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
const $ = window.jQuery;
const QssSdk = window.QssSdk;
const sm4 = window.sm4;
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const api = {
  getShareLoginInfo: "/showShare/getShareLoginInfo",
  loadFileList: "/showShare/loadFileList",
  createDownloadUrl: "/showShare/createDownloadUrl",
  download: "/api/showShare/download",
  cancelShare: "/share/cancelShare",
  saveShare: "/showShare/saveShare",
};

const shareId = route.params.shareId;
const shareInfo = ref({});
let keyId = [];
let filestream = "";
let fileName = "";
const getShareInfo = async () => {
  let result = await proxy.Request({
    url: api.getShareLoginInfo,
    showLoading: false,
    params: {
      shareId,
    },
  });
  if (!result) {
    return;
  }
  if (result.data == null) {
    router.push("/shareCheck/" + shareId);
    return;
  }
  shareInfo.value = result.data;
  console.log("shareInfo:", shareInfo.value);
  keyId = shareInfo.value.keyIds;
  filestream = shareInfo.value.filestream;
  fileName = shareInfo.value.fileName;
  console.log("fileName:", fileName)
  // console.log("filestream:",filestream);
  console.log("keyIds:", keyId);
};
getShareInfo();

//列表
const columns = [
  {
    label: "文件名",
    prop: "fileName",
    scopedSlots: "fileName",
  },
  {
    label: "修改时间",
    prop: "lastUpdateTime",
    width: 200,
  },
  {
    label: "大小",
    prop: "fileSize",
    scopedSlots: "fileSize",
    width: 200,
  },
];
const tableData = ref({});
const tableOptions = {
  extHeight: 80,
  selectType: "checkbox",
};

const loadDataList = async () => {
  let params = {
    pageNo: tableData.value.pageNo,
    pageSize: tableData.value.pageSize,
    shareId: shareId,
    filePid: currentFolder.value.fileId,
  };
  let result = await proxy.Request({
    url: api.loadFileList,
    params,
  });
  if (!result) {
    return;
  }
  tableData.value = result.data;
};
//展示操作按钮
const showOp = (row) => {
  tableData.value.list.forEach((element) => {
    element.showOp = false;
  });
  row.showOp = true;
};

const cancelShowOp = (row) => {
  row.showOp = false;
};

//多选 批量选择
const selectFileIdList = ref([]);
const rowSelected = (rows) => {
  selectFileIdList.value = [];
  rows.forEach((item) => {
    selectFileIdList.value.push(item.fileId);
  });
};

//目录
const currentFolder = ref({ fileId: 0 });
const navChange = (data) => {
  const { curFolder } = data;
  currentFolder.value = curFolder;
  loadDataList();
};

//查看
const previewRef = ref();
const navigationRef = ref();
const preview = (data) => {
  if (data.folderType == 1) {
    navigationRef.value.openFolder(data);
    return;
  }
  data.shareId = shareId;
  previewRef.value.showPreview(data, 2);
};

function getPhoneFromCookie() {
  // 获取名为 userInfo 的 cookie
  const match = document.cookie.match(new RegExp('(^| )userInfo=([^;]+)'));
  if (match) {
    // 解码并解析 JSON
    const userInfo = JSON.parse(decodeURIComponent(match[2]));
    return userInfo.phone;
  }
  return '';
}
//解密mackey，实际生产环境由后台服务解密并返回
function decryptMacKey(orgKey, macKey) {
  let macKeyAndCheck = QssSdk.hex2u8ab(macKey);
  let mackey = macKeyAndCheck.slice(0, 16);
  let macchk = macKeyAndCheck.slice(16);
  let orgMacKey = sm4.decrypt(mackey, orgKey, {
    padding: 'none',
    mode: 'ecb',
    output: 'array'
  });
  let hexMacKey = QssSdk.ab2hex(orgMacKey);
  console.log('解密MacKey:', hexMacKey);
  let data = new Uint8Array(16).fill(0x00);
  let check = QssSdk.calcHMac(hexMacKey, data).slice(0, 8);
  if (check.toString() == macchk.toString()) {
    QssSdk.setOrgMacKey(hexMacKey);
    return true;
  } else {
    // showLog("mackey校验失败");
  }
  return false;
};

//下载文件
const download = async (fileId) => {
  try {
    // 获取随机数和鉴权
    let random = "";

    // Get random number
    const randomPromise = new Promise((resolve, reject) => {
      QssSdk.getRandom(16, function (code, data) {
        if (code === QssSdk.ErrCode.STATUS_OK) {
          resolve(data);
        } else {
          reject(new Error('Failed to get random number'));
        }
      });
    });
    random = await randomPromise;
    console.log("Random number:", random);

    // Apply authentication
    const orgCode = "3401043927530314";
    const orgKey = "8C0F01FA42ACF6FD0B58373934E42F6F";

    if (!orgCode || !orgKey) {
      throw new Error("机构应用代码或密钥不能为空");
    }

    let randomAb = QssSdk.hex2u8ab(random);
    let challenge = sm4.encrypt(randomAb, orgKey, {
      padding: 'none',
      mode: 'ecb'
    });
    console.log("Challenge:", challenge);

    const phone = getPhoneFromCookie();
    console.log("Phone from cookie:", phone);

    const authPromise = new Promise((resolve, reject) => {
      const myOptions = {
        orgCode: orgCode,
        challenge: challenge,
        appName: "CtqKmsPriApp",
        appID: "zdxlz_demo",
        account: phone,
      };
      console.log("Auth options:", myOptions);

      QssSdk.initAuth(myOptions, function (code, data) {
        console.log("Auth response code:", code);
        console.log("Auth response data:", data);
        if (code === QssSdk.ErrCode.STATUS_OK) {
          if (decryptMacKey(orgKey, data.macKey)) {
            $("#KeyHandleSelect").empty();
            $("#KeyHandleSelect").prepend("<option value='0'>选择密钥句柄</option>");
            resolve(data);
          } else {
            reject(new Error('MacKey validation failed'));
          }
        } else {
          reject(new Error('Authentication failed: ' + code));
        }
      });
    });

    await authPromise;
    const sessionKeyHandle = ref("");  // 使用ref声明
    function Uint8ArrayToString(byteArray) {
      const decoder = new TextDecoder();
      return decoder.decode(byteArray);
    }
    // 获取句柄
    await new Promise((resolve, reject) => {
      QssSdk.querySessionKey(keyId, function (code, data) {
        if (code == QssSdk.ErrCode.STATUS_OK) {
          $("#KeyHandleSelect").append("<option value='" + data.sessionKeyHandle + "'>" + data.sessionKeyHandle + "</option>");
          sessionKeyHandle.value = data.sessionKeyHandle;
          console.log("句柄:", data.sessionKeyHandle);
          resolve(data);
        } else {
          reject(new Error('Failed to query session key'));
        }
      });
    });

    // 解密文件
    if (sessionKeyHandle.value === "0") {
      // showLog("请选择密钥句柄！！！");
      return;
    }
    let fileEncryption = filestream;

    if (fileEncryption == "" || fileEncryption == null) {
      // showLog("待解密数据不能为空！！！");
      return;
    }
    let cipherData = QssSdk.hex2u8ab(fileEncryption);
    QssSdk.qcDecrypt(sessionKeyHandle.value, 1025, 1, null, cipherData, function (code, data) {
      // showLog("===================== qcDecrypt =====================");
      // showLog('code:{0}', code);
      console.log("解密数据:", data);
      if (code == QssSdk.ErrCode.STATUS_OK) {
        console.log("解密数据成功");
        data = Uint8ArrayToString(data);
        // showLog("解密数据成功");
        // 8进制数据 -> 2进制数据
        const byteCharacters = atob(data);  // 解码
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        // 创建 Blob 对象
        const blob = new Blob([byteArray]);

        // 创建一个临时链接用于下载
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName;

        document.body.appendChild(link);
        link.click();

        // 清理临时元素
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);

        // let blob = new Blob([data], { type: 'application/octet-stream' }); // 假设文件类型为二进制流
        // let url = URL.createObjectURL(blob);
        // let a = document.createElement('a');
        // a.style.display = 'none';
        // a.href = url;
        // a.download = uploadedFileInfo.name; // 设置下载文件名，可以根据需要修改
        // document.body.appendChild(a);
        // a.click();
        // window.URL.revokeObjectURL(url); // 释放URL对象


      } else {
        // showLog("解密数据失败，" + data);
      }



    });



    // let result = await proxy.Request({
    //   url: api.createDownloadUrl + "/" + shareId + "/" + fileId,
    // });

    // if (!result) {
    //   throw new Error('Failed to create download URL');
    // }

    // window.location.href = api.download + "/" + result.data;
  } catch (error) {
    console.error('Download error:', error);
    proxy.Message.error('下载失败：' + (error.message || '未知错误'));
  }
};


//保存到我的网盘
const folderSelectRef = ref();
const save2MyPanFileIdArray = [];
const save2MyPan = () => {
  if (selectFileIdList.value.length == 0) {
    return;
  }
  if (!proxy.VueCookies.get("userInfo")) {
    router.push("/login?redirectUrl=" + route.path);
    return;
  }
  save2MyPanFileIdArray.values = selectFileIdList.value;
  folderSelectRef.value.showFolderDialog();
};
const save2MyPanSingle = (row) => {
  if (!proxy.VueCookies.get("userInfo")) {
    router.push("/login?redirectUrl=" + route.path);
    return;
  }
  save2MyPanFileIdArray.values = [row.fileId];
  folderSelectRef.value.showFolderDialog();
};
//执行保存操作
const save2MyPanDone = async (folderId) => {
  let result = await proxy.Request({
    url: api.saveShare,
    params: {
      shareId: shareId,
      shareFileIds: save2MyPanFileIdArray.values.join(","),
      myFolderId: folderId,
    },
  });
  if (!result) {
    return;
  }
  loadDataList();
  proxy.Message.success("保存成功");
  folderSelectRef.value.close();
};

//取消分享
const cancelShare = () => {
  proxy.Confirm(`你确定要取消分享吗？`, async () => {
    let result = await proxy.Request({
      url: api.cancelShare,
      params: {
        shareIds: shareId,
      },
    });
    if (!result) {
      return;
    }
    proxy.Message.success("取消分享成功");
    router.push("/");
  });
};

const jump = () => {
  router.push("/");
};
</script>

<style lang="scss" scoped>
@import "@/assets/file.list.scss";

.header {
  width: 100%;
  position: fixed;
  background: #0c95f7;
  height: 50px;

  .header-content {
    width: 70%;
    margin: 0px auto;
    color: #fff;
    line-height: 50px;

    .logo {
      display: flex;
      align-items: center;
      cursor: pointer;

      .icon-pan {
        font-size: 40px;
      }

      .name {
        font-weight: bold;
        margin-left: 5px;
        font-size: 25px;
      }
    }
  }
}

.share-body {
  width: 70%;
  margin: 0px auto;
  padding-top: 50px;

  .loading {
    height: calc(100vh / 2);
    width: 100%;
  }

  .share-panel {
    margin-top: 20px;
    display: flex;
    justify-content: space-around;
    border-bottom: 1px solid #ddd;
    padding-bottom: 10px;

    .share-user-info {
      flex: 1;
      display: flex;
      align-items: center;

      .avatar {
        margin-right: 5px;
      }

      .share-info {
        .user-info {
          display: flex;
          align-items: center;

          .nick-name {
            font-size: 15px;
          }

          .share-time {
            margin-left: 20px;
            font-size: 12px;
          }
        }

        .file-name {
          margin-top: 10px;
          font-size: 12px;
        }
      }
    }
  }
}

.file-list {
  margin-top: 10px;

  .file-item {
    .op {
      width: 170px;
    }
  }
}
</style>
